package org.teremail.smtp.commands;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.teremail.message.Address;
import org.teremail.message.AddressFormatException;
import org.teremail.message.AddressParser;
import org.teremail.smtp.SMTPCommandFactory;
import org.teremail.smtp.SMTPSession;

/**
 * Mail command, handles MAIL FROM: requests.  The FROM portion of the
 * request will be handled as a single parameter.
 * 
 * @author Michael Barker
 *
 */
public class MAILCommand extends SMTPCommand {

    private final static Pattern FROM_PATTERN = Pattern.compile("FROM:(.*)");
    private final static String MSG_501_INVALID_ADDRESS = "501 Invalid return path";
    private static final String MSG_501_MISSING_ADDRESS = "501 No return path specified";
    public MAILCommand(List<String> parameters) {
        super("MAIL", parameters);
    }
    
    
    @Override
    public void process(SMTPSession session) {
        
        try {
            if (getParameters().size() > 0) {
                
                Matcher m = FROM_PATTERN.matcher(getParameters().get(0));
                if (m.matches() && m.groupCount() == 1) {
                    String addressStr = m.group(1);
                    Address address = AddressParser.parseSMTP(addressStr);
                    
                    session.setSender(address);
                    session.clearRecipients();
                    session.clearData();
                    session.write(MSG_OK);
                }
                
            } else {
                session.write(MSG_501_MISSING_ADDRESS);
            }
        } catch (AddressFormatException e) {
            session.write(MSG_501_INVALID_ADDRESS);
        }
    }


    public static final SMTPCommandFactory FACTORY = new SMTPCommandFactory() {
        public SMTPCommand create(List<String> parameters) {
            return new MAILCommand(parameters);
        }
    };

}
